import storage, {load} from '@/config/storage';
import {Effect, Model, SubscriptionsMapObject} from 'dva-core-ts';
import {Reducer} from 'redux';
import {RootState} from '@/models/index';

export interface SoundsHistory {
  id: string;
  title: string;
  thumbnailUrl: string;
  currentTime: number;
  duration: number;
  rate: number;
}

interface SoundsHistoryModelState {
  soundsHistory: SoundsHistory[];
}

interface CategoryModel extends Model {
  namespace: 'soundsHistory';
  state: SoundsHistoryModelState;
  effects: {
    ready: Effect;
    add: Effect;
    set: Effect;
    delete: Effect;
  };
  reducers: {
    setState: Reducer<SoundsHistoryModelState>;
  };
  subscriptions?: SubscriptionsMapObject;
}

const initialState = {
  soundsHistory: [],
};

const soundsHistoryModel: CategoryModel = {
  namespace: 'soundsHistory',
  state: initialState,
  reducers: {
    setState(state, {payload}) {
      return {
        ...state,
        ...payload,
      };
    },
  },
  effects: {
    *ready(_, {call, put}) {
      const soundsHistory = yield call(load, {key: 'soundsHistory'});
      // console.log(
      //   'soundsHistory--------------------------------------------------',
      //   soundsHistory,
      // );
      yield put({
        type: 'setState',
        payload: {soundsHistory},
      });
    },
    *add({payload}, {put, select}) {
      // console.log(
      //   'soundsHistoryAdd--------------------------------------------------',
      // );
      // const soundsHistory = yield call(load, {key: 'soundsHistory'});
      let {soundsHistory} = yield select(
        ({soundsHistory}: RootState) => soundsHistory,
      );
      let newSoundsHistory = [];
      if (soundsHistory?.length > 0) {
        newSoundsHistory = soundsHistory.concat(payload.data);
      } else {
        newSoundsHistory = [payload.data];
      }
      yield put({
        type: 'setState',
        payload: {soundsHistory: newSoundsHistory},
      });
      storage.save({
        key: 'soundsHistory',
        data: newSoundsHistory,
      });
    },
    *set({payload}, {put, select}) {
      // console.log(
      //   'soundsHistorySet---------------------------------------------------',
      // );
      let {soundsHistory}: SoundsHistoryModelState = yield select(
        ({soundsHistory}: RootState) => soundsHistory,
      );
      const {data} = payload;
      let newSoundsHistory = soundsHistory.map(item => {
        if (item.id === data.id) {
          return {
            ...item,
            rate:
              data.currentTime && data.duration > 0
                ? Math.floor(((data.currentTime * 100) / data.duration) * 100) /
                  100
                : 0,
            ...payload.data,
          };
        }
        return item;
      });
      yield put({
        type: 'setState',
        payload: {soundsHistory: newSoundsHistory},
      });
      storage.save({
        key: 'soundsHistory',
        data: newSoundsHistory,
      });
    },
    *delete({payload}, {put, select}) {
      // console.log('delete');
      let {soundsHistory}: SoundsHistoryModelState = yield select(
        ({soundsHistory}: RootState) => soundsHistory,
      );
      let newSoundsHistory = soundsHistory.filter(
        item => item.id !== payload.data.id,
      );
      yield put({
        type: 'setState',
        payload: {soundsHistory: newSoundsHistory},
      });
      storage.save({
        key: 'soundsHistory',
        data: newSoundsHistory,
      });
    },
  },
  subscriptions: {
    setup({dispatch}) {
      dispatch({type: 'ready'});
    },
    asyncStorage() {
      storage.sync.soundsHistory = async () => {
        return null;
      };
    },
  },
};

export default soundsHistoryModel;
